package cn.edu.tju.elm.controller;

import cn.edu.tju.core.model.Authority;
import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.core.model.User;
import cn.edu.tju.core.utils.ObjectUtils;
import cn.edu.tju.elm.model.*;
import cn.edu.tju.core.model.HttpResult;
//import cn.edu.tju.elb.service.BusinessService;
//import cn.edu.tju.elb.service.FoodService;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.elm.repository.BusinessRepository;
import cn.edu.tju.elm.repository.CartRepository;
import cn.edu.tju.elm.repository.FoodRepository;
import cn.edu.tju.elm.repository.OrderRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/foods")
@Tag(name = "管理商品")
public class FoodController {
    @Autowired
    private UserService userService;
    @Autowired
    private BusinessRepository businessRepository;
    @Autowired
    private FoodRepository foodRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private CartRepository cartRepository;

//    @Autowired
//    private FoodService foodService;
//
//    @Autowired
//    private BusinessService businessService;

    @GetMapping("/{id}")
    @Operation(summary = "返回查询到的一条商品记录", method = "GET")
    public HttpResult<Food> getFoodById(@PathVariable Long id){
        try {
            // 1. 获取当前登录用户（用于权限验证）
            User currentUser = userService.getUserWithAuthorities()
                    .orElseThrow(() -> new RuntimeException("用户未登录"));

            // 2. 查询商品
            Optional<Food> foodOpt = foodRepository.findById(id);
            if (foodOpt.isEmpty()) {
                return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "商品不存在");
            }
            Food food = foodOpt.get();

            // 3. 权限验证（管理员或商家所有者可以查看）
            boolean isAdmin = currentUser.getAuthorities().stream()
                    .anyMatch(auth -> "ADMIN".equals(auth.getName()));

            boolean isBusinessOwner = food.getBusiness() != null
                    && food.getBusiness().getBusinessOwner().getId().equals(currentUser.getId());

            if (!isAdmin && !isBusinessOwner) {
                return HttpResult.failure(ResultCodeEnum.NOT_AUTHORIZED, "无权查看此商品");
            }

            // 4. 返回查询结果
            return HttpResult.success(food);

        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SYSTEM_ERROR, "查询商品失败: " + e.getMessage());
        }
    }

    @GetMapping("")
    public HttpResult<List<Food>> getAllFoods(@RequestParam(name = "business", required = false) Long businessId,
                                              @RequestParam(name = "order", required = false) Long orderId){
        try {
            List<Food> foods = List.of();

            // 情况1：同时提供订单ID和店铺ID
            if (businessId != null && orderId != null) {
                // 验证店铺是否存在
                if (!businessRepository.existsById(businessId)) {
                    return HttpResult.failure(ResultCodeEnum.BUSINESS_NOT_FOUND);
                }

                // 验证订单是否存在
                Optional<Order> orderOpt = orderRepository.findById(orderId);
                if (orderOpt.isEmpty()) {
                    return HttpResult.failure(ResultCodeEnum.NOT_FOUND);
                }

                // 验证订单是否属于该店铺
                Order order = orderOpt.get();
                if (!order.getBusiness().getId().equals(businessId)) {
                    return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "订单不属于该店铺");
                }


            }
            // 情况2：只提供店铺ID
            else if (businessId != null) {
                // 验证店铺是否存在
                if (!businessRepository.existsById(businessId)) {
                    return HttpResult.failure(ResultCodeEnum.BUSINESS_NOT_FOUND);
                }

                foods = foodRepository.findByBusinessId(businessId);

            }

            // 情况4：两个参数都未提供
            else {
                return HttpResult.failure(ResultCodeEnum.PARAM_ERROR, "请提供店铺ID或订单ID");
            }

            return HttpResult.success(foods);

        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SYSTEM_ERROR, "查询商品列表失败: " + e.getMessage());
        }

        }



    @PostMapping("")
    @Operation(summary = "增加商品", description = "需要当前用户拥有新增商品的店铺的权限才可新增")
    public HttpResult<Food> addFood(@RequestBody Food food) {
        User user = userService.getUserWithAuthorities().get();
        Business business = businessRepository.findById(food.getBusiness().getId()).orElse(null);
        // 非管理 也非店铺拥有者 无法新增
        boolean ADMIN = false;
        for (Authority authority : user.getAuthorities()) {
            if ("ADMIN".equals(authority.getName())) {
                ADMIN = true;
            }
        }
        if (!ADMIN) {
            if (business == null || !business.getBusinessOwner().getId().equals(user.getId())) {
                return HttpResult.failure(ResultCodeEnum.NOT_AUTHORIZED);
            }
        }
        Food newFood = new Food();
        ObjectUtils.newObjectDefaultInit(newFood, user);
        newFood.setFoodName(food.getFoodName());
        newFood.setFoodPrice(food.getFoodPrice());
        newFood.setBusiness(business);
        return HttpResult.success(foodRepository.save(newFood));
    }



    @PatchMapping("/{id}")
    @Operation(summary = "修改商品信息",method = "PATCH")
    public HttpResult<Food> patchBusiness (@PathVariable Long id, @RequestBody FoodUpdateRequest updateRequest){

        User currentUser = userService.getUserWithAuthorities()
                .orElseThrow(() -> new RuntimeException("用户未登录或不存在"));

        // 2. 查找商品信息
        Optional<Food> existingFoodOpt = foodRepository.findById(id);
        if (existingFoodOpt.isEmpty()) {
            return HttpResult.failure(ResultCodeEnum.NOT_FOUND);
        }

        Food existingFood = existingFoodOpt.get();

        // 3. 权限验证：直接比较当前用户ID和商品的business关联的用户ID
        // 假设Business实体中有getUser()或类似方法获取关联的用户
        if (!existingFood.getBusiness().getBusinessOwner().getId().equals(currentUser.getId())) {
            return HttpResult.failure(ResultCodeEnum.NOT_AUTHORIZED);
        }


            // 部分更新逻辑：只更新传入的字段
            if (updateRequest.getFoodName() != null) {
                existingFood.setFoodName(updateRequest.getFoodName());
            }
            if (updateRequest.getFoodExplain() != null) {
                existingFood.setFoodExplain(updateRequest.getFoodExplain());
            }
            if (updateRequest.getFoodImg() != null) {
                existingFood.setFoodImg(updateRequest.getFoodImg());
            }
            if (updateRequest.getFoodPrice() != null) {
                existingFood.setFoodPrice(updateRequest.getFoodPrice());
            }
            if (updateRequest.getRemarks() != null) {
                existingFood.setRemarks(updateRequest.getRemarks());
            }

            // 保存更新
            Food updatedFood = foodRepository.save(existingFood);
            return HttpResult.success(updatedFood);


    }





}

